﻿using System;
using System.Collections.Generic;
using System.Text;
using SdmxMl.Manager;
using SdmxMl.Common;
using SdmxMl.Structure;

namespace SdmxMl.Fact_Dim
{
    public class CollectDsdInfo
    {
        private SmManager sm;
        private KeyFamilyType dsd;
        private RefNomen refVarHelper;

        public CollectDsdInfo(SmManager s, KeyFamilyType kf)
        {
            sm = s;
            dsd = kf;

            // The container must hold the DSD to work with
            if (sm == null || dsd == null)
                throw new ApplicationException("Invalid. No DSD received.");

            sm.PutArtefact(SdmxArtefactType.KeyFamilies, dsd);
            refVarHelper = new RefNomen(sm);

        }


        public string CreateOracleSql()
        {
            StringBuilder sb = new StringBuilder(1024);

            // Collect
            List<BaseDimensionType> lbd = refVarHelper.PrepareVarList(dsd, true);
            ListVarFlags listFlags = refVarHelper.listFlags;

            List<NomenWithQuality> listNomenConcepts = refVarHelper.GetListOfNomen(dsd);

            // Creates a dictionary of all DIM to create
            Dictionary <string, NomenWithQuality> dicoDimCodes = new Dictionary<string,NomenWithQuality>();
            foreach (NomenWithQuality nmq in listNomenConcepts)
                if (nmq.IsEmpty == false && dicoDimCodes.ContainsKey(nmq.KeyId) == false)
                    dicoDimCodes.Add(nmq.KeyId, nmq);

            OraFactDim oraSql = new OraFactDim(refVarHelper);

            sb.Append(oraSql.CreateDrop(dsd, dicoDimCodes));
            sb.Append(oraSql.CreateFact(dsd, lbd));

            // All DIM
            foreach (NomenWithQuality nq in dicoDimCodes.Values)
            {
                if (nq.IsEmpty == false)
                {
                    if (nq.IsHierarchicalCodelist)
                        sb.Append(oraSql.CreateDimHierarchyCode(nq));
                    else
                        sb.Append(oraSql.CreateDimCode(nq));
                }
            }

            // Now Flag Treatment (Code, ConceptId, Type)
            sb.Append(oraSql.CreateFLagsInfo(dsd, listFlags));

            // And link from concept to DIM
            sb.Append(oraSql.CreateLinkInfo(dsd, lbd, listNomenConcepts));
            

            return sb.ToString();
        }
    }
}
